import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as fs from 'fs';
import * as dotenv from 'dotenv';
import { ConfigEnum } from '@/enum/config.enum';
import { ConfigService } from '@nestjs/config';

// 通过环境变量读取不同的.env文件
export function getEnv(env: string): Record<string, unknown> {
    if (fs.existsSync(env)) {
        return dotenv.parse(fs.readFileSync(env));
    }
    return {};
}

export function getServerConfig() {
    const defaultConfig = getEnv('.env');
    const envConfig = getEnv(`.env.${process.env.NODE_ENV || 'development'}`);
    // configService
    return { ...defaultConfig, ...envConfig };
}

// 通过dotENV来解析不同的配置
export function buildConnectionOptions(configService: ConfigService) {
    // configService
    const config = getServerConfig();
    // const logFlag = config["LOG_ON"] === "true";
    const entitiesDir =
        process.env.NODE_ENV === 'test'
            ? [__dirname + '/**/*.entity.ts']
            : [__dirname + '/**/*.entity{.js,.ts}'];
    // console.log("entitiesDir", entitiesDir);
    return {
        type: config[ConfigEnum.DB_TYPE],
        host: config[ConfigEnum.DB_HOST],
        port: config[ConfigEnum.DB_PORT],
        username: config[ConfigEnum.DB_USERNAME],
        password: config[ConfigEnum.DB_PASSWORD],
        database: config[ConfigEnum.DB_DATABASE],
        entities: entitiesDir,
        // entities: [User, Profile, Roles],
        // 同步本地的schema与数据库 -> 初始化的时候去使用
        synchronize: configService.get(ConfigEnum.DB_SYNC),
        logging: configService.get(ConfigEnum.DB_LOG_ON),
        timezone: config[ConfigEnum.TIME_ZONE],// 保存为本地时区
        // 添加全局表名前缀
        // entityPrefix: configService.get('TABLE_PREFIX') || '', // 读取环境变量中的前缀
    } as TypeOrmModuleOptions;
}

// export const connectionParams = buildConnectionOptions();

// export default new DataSource({
// 	...connectionParams,
// 	// migrations: ['src/migrations/**'],
// 	subscribers: []
// } as DataSourceOptions);
